package com.millstein.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.millstein.realtime.app.base.BaseAppV1;
import com.millstein.realtime.bean.TrafficHomeDetailPageViewBean;
import com.millstein.realtime.common.Constants;
import com.millstein.realtime.util.CommonUtil;
import com.millstein.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Description
 * @Author tsing
 * @Date 2024-10-21 13:48
 */
public class Dws_03_TrafficPageViewWindow extends BaseAppV1 {

    public static void main(String[] args) {
        new Dws_03_TrafficPageViewWindow().init(
                8003,
                2,
                "Dws_03_TrafficPageViewWindow",
                Constants.TOPIC_DWD_TRAFFIC_PAGE
        );
    }

    /**
     * 具体数据处理的逻辑，由子类编写
     *
     * @param env          执行环境对象
     * @param streamSource 待处理的数据流
     */
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> streamSource) {
        // 1. 先找到详情页和首页，封装到bean
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream = findUv(streamSource);
        // 2. 开窗聚合
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream = windowAndAgg(beanStream);
        // 3. 写到doris中
        writeToDoris(resultStream);
    }

    /**
     * 找出首页和详情页的uv记录
     * @param streamSource 读取的page流
     * @return
     */
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> findUv(DataStreamSource<String> streamSource) {
        return streamSource
                .map(new MapFunction<String, JSONObject>() {
                    @Override
                    public JSONObject map(String value) throws Exception {
                        return JSONObject.parseObject(value);
                    }
                })
                .filter(new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        String pageId = value.getJSONObject("page").getString("page_id");
                        return "home".equals(pageId) || "good_detail".equals(pageId);
                    }
                })
                .keyBy(item -> item.getJSONObject("common").getString("uid"))
                .process(new KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>() {

                    ValueState<String> homeDateState;
                    ValueState<String> goodsDetailDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        homeDateState = getRuntimeContext().getState(
                                new ValueStateDescriptor<>("home-date-state", String.class)
                        );
                        goodsDetailDateState = getRuntimeContext().getState(
                                new ValueStateDescriptor<>("goods-detail-date-state", String.class)
                        );
                    }

                    @Override
                    public void processElement(
                            JSONObject value,
                            Context ctx,
                            Collector<TrafficHomeDetailPageViewBean> out
                    ) throws Exception {
                        String pageId = value.getJSONObject("page").getString("page_id");
                        String etDate = CommonUtil.formatDate(value.getLong("ts"));
                        String homeDate = homeDateState.value();
                        String detailDate = goodsDetailDateState.value();
                        if ("home".equals(pageId) && !etDate.equals(homeDate)) {
                            homeDateState.update(etDate);
                            out.collect(
                                    TrafficHomeDetailPageViewBean.builder()
                                            .homeUvCt(1L)
                                            .goodDetailUvCt(0L)
                                            .ts(value.getLong("ts"))
                                            .build()
                            );
                        } else if ("good_detail".equals(pageId) && !etDate.equals(detailDate)) {
                            goodsDetailDateState.update(etDate);
                            out.collect(
                                    TrafficHomeDetailPageViewBean.builder()
                                            .homeUvCt(0L)
                                            .goodDetailUvCt(1L)
                                            .ts(value.getLong("ts"))
                                            .build()
                            );
                        }
                    }
                });
    }

    /**
     * 窗口聚合
     * @param beanStream 过滤出来的uv数据流
     * @return
     */
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> windowAndAgg(
            SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream
    ) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TrafficHomeDetailPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<TrafficHomeDetailPageViewBean>() {
                                    @Override
                                    public long extractTimestamp(TrafficHomeDetailPageViewBean element, long recordTimestamp) {
                                        return element.getTs();
                                    }
                                })
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                            @Override
                            public TrafficHomeDetailPageViewBean reduce(
                                    TrafficHomeDetailPageViewBean value1,
                                    TrafficHomeDetailPageViewBean value2
                            ) throws Exception {
                                value1.setHomeUvCt(value1.getHomeUvCt() + value2.getHomeUvCt());
                                value1.setGoodDetailUvCt(value1.getGoodDetailUvCt() + value2.getGoodDetailUvCt());
                                return value1;
                            }
                        },
                        new ProcessAllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                            @Override
                            public void process(
                                    Context context,
                                    Iterable<TrafficHomeDetailPageViewBean> elements,
                                    Collector<TrafficHomeDetailPageViewBean> out
                            ) throws Exception {
                                TrafficHomeDetailPageViewBean bean = elements.iterator().next();
                                String startTime = CommonUtil.formatTime(context.window().getStart());
                                String endTime = CommonUtil.formatTime(context.window().getEnd());
                                String curDate = startTime.substring(0, 10);
                                bean.setStt(startTime);
                                bean.setEdt(endTime);
                                bean.setCurDate(curDate);
                                out.collect(bean);
                            }
                        });
    }

    /**
     * 将结果写到doris中
     * @param resultStream 处理结果
     */
    private void writeToDoris(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream) {
        resultStream
                .map(bean -> {
                    SerializeConfig config = new SerializeConfig();
                    config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
                    return JSON.toJSONString(bean, config);
                })
                .addSink(FlinkSinkUtil.getDorisSink("gmall.dws_traffic_page_view_window"));
    }
}
